from world import merchant, town
from world import movement
import pygame
import event

GOOD_KEYS = {pygame.K_f:town.FOOD,
             pygame.K_m:town.MINERALS,
             pygame.K_l:town.LUMBER}

class _ArrowTurnEnder(object):
    def __init__(self, engine, actor):
        self.engine = engine
        self.actor = actor
    def up(self): self.end_turn()
    def down(self): self.end_turn()
    def left(self): self.end_turn()
    def right(self): self.end_turn()
    def key_pressed(self, key):
        if key in GOOD_KEYS.keys():
            self.end_turn()
    def end_turn(self):
        if self.actor.next_action:
            self.engine.do_turn()
    



class ArrowMerchant(merchant.PuppetMerchant):
    
    def up(self):
        """
        Called when the up button is pressed, assigns this merchant a move
        north action.
        """
        self._assign_move_action(movement.NORTH)
        
    def down(self):
        """
        Called when the down button is pressed, assigns this merchant a move
        south action.
        """
        self._assign_move_action(movement.SOUTH)
        
    def left(self):
        """
        Called when the left button is pressed, assigns this merchant a move
        west action.
        """
        self._assign_move_action(movement.WEST)
        
        
    def right(self):
        """
        Called when the right button is pressed, assigns this merchant a move
        east action.
        """
        self._assign_move_action(movement.EAST)
        
    def key_pressed(self, key):
        """
        Called when one of the GOOD_KEYS is pressed
        """
        action = None
        if self.goods:
            action = merchant.get_sell_action(self, GOOD_KEYS[key])
        else:
            action = merchant.get_buy_action(self, GOOD_KEYS[key])
        self.set_action(action)
        
    def _assign_move_action(self, direction):
        """
        Assigns this merchant a move action based on a given direction.
        """
        action = merchant.get_move_action(self, direction)
        self.set_action(action)
        
    def get_assign_handler(self):
        """
        Gets an event handler that assigns actions to this merchant based on
        arrow keys
        """
        last = None
        
        for key in GOOD_KEYS.keys():
            last = event.KeyHandler(self, key, last)
        return event.ArrowHandler(self, last)
        
    def get_end_turn_handler(self, engine):
        """
        Gets an event handler that assigns actions to this merchant and ends the
        turn immediately afterwards
        """
        arrower = _ArrowTurnEnder(engine, self)
        
        h1 = self.get_assign_handler()
        
        last = event.ArrowHandler(arrower, h1)
        for key in GOOD_KEYS.keys():
            last = event.KeyHandler(arrower, key, last)
        return last
        
    
        